<!--
 * @Description: 
 * @Author: ouyaping
 * @Date: 2025-10-05 22:34:42
 * @LastEditors: ouyaping
 * @LastEditTime: 2025-10-08 18:08:09
-->
<template>
    <div class="iotdeviceAdd-page">
        <el-form ref="ruleFormRef" :model="from" :rules="rules" label-width="auto" :inline="true">
            <el-form-item prop="deptId">
                <el-cascader v-model="from.deptId" :options="options" :props="props" @change="handleChange"
                    placeholder="所属机构" />
            </el-form-item>
            <el-form-item prop="deviceCode">
                <el-input v-model="from.deviceCode" style="width: 240px" placeholder="请输入设备编码" />
            </el-form-item>
            <el-form-item prop="address">
                <el-input v-model="from.address" style="width: 240px" placeholder="请输入详细设备安装位置" />
            </el-form-item>
            <el-form-item prop="ld">
                <el-input v-model="from.ld" style="width: 240px" placeholder="请选择经纬度,以/分割" />
            </el-form-item>
        </el-form>
        <div id="controller" style="width: 100%; height:600px;"></div>

        <el-space wrap style="margin-top: 30px;display: flex;
        justify-content: flex-end;">
            <el-button @click="clearAdd">取消</el-button>
            <el-button type="primary" @click="submitAdd">确定</el-button>
        </el-space>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onBeforeUnmount } from 'vue'

const emit = defineEmits(['submitAdd', 'clearAdd'])
const definePropsInfo = defineProps({
    options: {
        type: Array,
        default: () => ([])
    },
    fromItem: {
        type: Object,
        default: () => (null)
    }
})
const props = {
    expandTrigger: 'hover' as const,
    checkStrictly: true,
    value: 'id',
    label: 'title'
}
const from = ref({
    deptId: null,
    deviceCode: '',
    address: '',
    ld: ''
})
const ruleFormRef = ref()
const rules = reactive({
    deptId: [
        {
            required: true,
            message: '请选择所属机构',
            trigger: 'change',
        }],
    deviceCode: [
        {
            required: true,
            message: '请输入设备编码',
            trigger: 'change',
        }],
    address: [
        {
            required: true,
            message: '请输入详细设备安装位置',
            trigger: 'change',
        }],
    ld: [
        {
            required: true,
            message: '请选择经纬度',
            trigger: 'change',
        }],
})
if (definePropsInfo.fromItem) {
    from.value = {
        id: definePropsInfo.fromItem.id,
        deptId: definePropsInfo.fromItem.deptId,
        deviceCode: definePropsInfo.fromItem.deviceCode,
        address: definePropsInfo.fromItem.address,
        ld: `${definePropsInfo.fromItem.longitude}/${definePropsInfo.fromItem.dimension}`
    }
}
const handleChange = (value) => {
    console.log(value)
    from.value.deptId = value[value.length - 1]
    console.log(from.value.deptId)
}

const map = ref(null)
const zoom = 11.5


// 添加标记的辅助函数
const addMarker = (point) => {
    // 创建标记对象
    const marker = new T.Marker(point);
    // 向地图添加标记
    map.value.addOverLay(marker);
};

// 获取坐标的回调函数
const getLngLat = (lnglat) => {
    // 清除现有覆盖物
    map.value.clearOverLays();

    // 添加新的标记
    addMarker(lnglat);

    // 更新坐标值（保留6位小数）
    const longLat = {
        lng: lnglat.lng.toFixed(6),
        lat: lnglat.lat.toFixed(6)
    };

    // 更新表单值
    from.value.ld = `${longLat.lng}/${longLat.lat}`;
};
// 初始化地图
const initMap = () => {
    // 如果存在初始坐标，则添加标记
    const longLat = from.value.ld ? {
        lat: from.value.ld.split('/')[1],
        lng: from.value.ld.split('/')[0]
    } : null
    // 创建地图实例
    map.value = new T.Map('controller');

    // 设置初始中心点和缩放级别
    const initialPoint = new T.LngLat(longLat ? longLat.lng : 115.38948, longLat ? longLat.lat : 40.84728);
    map.value.centerAndZoom(initialPoint, zoom);

    // 清除所有覆盖物
    map.value.clearOverLays();

    // 初始化坐标拾取器
    const cp = new T.CoordinatePickup(map.value, {
        callback: getLngLat,  // 点击事件回调函数
        showType: 'single'    // 单次点击模式
    });
    cp.addEvent()

    if (longLat) {
        addMarker(longLat);
    }
};


setTimeout(() => {
    initMap()
}, 500);

// 取消
const clearAdd = () => {
    emit('clearAdd')
}
// 确定
const submitAdd = async () => {
    if (!ruleFormRef.value) return
    await ruleFormRef.value.validate((valid, fields) => {
        if (valid) {
            const longitude = from.value.ld.split('/')[0]
            const dimension = from.value.ld.split('/')[1]
            emit('submitAdd', {
                ...from.value,
                longitude,
                dimension
            })
        } else {
            console.log('error submit!', fields)
        }
    })

}

onBeforeUnmount(() => {
    // 清空数据
    from.value = {
        deptId: null,
        deviceCode: '',
        address: '',
        ld: ''
    }
})

</script>

<style lang="scss">
.iotdeviceAdd-page {
    padding: 20px;

    #controller {
        margin-top: 10px;

    }
}
</style>
